package com.example;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ImageView.ScaleType;
import android.widget.ProgressBar;

public class DownloadFileFromURLs extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}
	
	public void StartDownload(View v) throws MalformedURLException {
		final String PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/images"; // "/mnt/external_sd/images";
		File f = new File(PATH);
		if(!f.exists()) {
			f.mkdir();
		} else {
//			for (File file : f.listFiles()) {
//				if(file.isFile()) {
//					file.delete();
//				}
//			}
		}
		
		EditText txtLinks = (EditText) findViewById(R.id.txtLinks);
		final String[] arrLink = txtLinks.getText().toString().split(";");
		progressBar = (ProgressBar) findViewById(R.id.progressBar1);
		
		URL[] arr = new URL[arrLink.length];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = new URL(arrLink[i]);
		}
		new Download().execute(arr);
	}
	
	ProgressBar progressBar;
	
	class Download extends AsyncTask<URL, Integer, Long> {

		String PATH;
		
		@Override
		protected Long doInBackground(URL... url) {
			PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/images"; // "/mnt/external_sd/images";
			File f = new File(PATH);
			f.mkdir();
			
			int i = 0;
			for (URL link : url) {
				downloadFromUrl(link, System.currentTimeMillis() + ".jpg", PATH);
				publishProgress(++i * 100 / url.length);
			}
			return (long)url.length;
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			progressBar.setProgress(values[0]);
		}
		
		@Override
		protected void onPostExecute(Long result) {
			GridLayout gridLayout = (GridLayout) findViewById(R.id.gridLayout);
			gridLayout.removeAllViews();
			int n = 3;
			gridLayout.setColumnCount(n);
			
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(gridLayout.getWidth() / n, 3 * gridLayout.getWidth() / (2 * n));			
			File f = new File(PATH);
			for (File file : f.listFiles()) {
				if(file.isFile() && (file.getName().endsWith(".jpg") || file.getName().endsWith(".png"))) {
					ImageView iv = new ImageView(getBaseContext());
					iv.setScaleType(ScaleType.FIT_XY);
					iv.setLayoutParams(params);
					Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
					iv.setImageBitmap(myBitmap);
					gridLayout.addView(iv);
				}
			}
		}
	}
	
	public void downloadFromUrl(URL url, String fileName, String folderPath) {
		try {
			// Mở kết nối tới URL
			URLConnection ucon = url.openConnection();
			// Tạo đối tượng InputStreams để đọc dữ liệu trong đối tượng ucon			 
			InputStream is = ucon.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			FileOutputStream fos = new FileOutputStream(folderPath + "/" + System.currentTimeMillis() + getExtension(url.toString()));
			int n = 0;
			byte[] b = new byte[4096];
			while ((n = bis.read(b)) > 0) {
				fos.write(b, 0, n);
			}
			bis.close();
			fos.flush();
			fos.close();
		} catch (IOException e) {
			Log.d("ImageManager", "Error: " + e);
		}
	}
	
	String getExtension(String fileUrl) {
		return fileUrl.substring(fileUrl.lastIndexOf('.'), fileUrl.length());
	}
}
